package com.thprojects.myphotomemories.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;

import android.net.http.AndroidHttpClient;
import android.util.Log;

public class RESTClient {

	/**
	 * 
	 * @param url complete url, ex. "http://www.example.com/blog/login.php"
	 * @return
	 * @throws IOException
	 */
	public static String post(String url, List<NameValuePair> params) throws IOException {
		
		AndroidHttpClient httpClient = AndroidHttpClient.newInstance("MyPhotoMemories");
		HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(new UrlEncodedFormEntity(params));

		HttpResponse response;
		
		try{
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			
			if (entity != null){
				InputStream is = entity.getContent();
				String res = convertStreamToString(is);
				is.close();
				Log.d("MPM", "RestClient: result="+res);
				return res;
			}
			else return null;
			
		} 
		finally{
			httpClient.close();
		}
	}

	private static String convertStreamToString(InputStream is) {
		
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException ioe) {
        	Log.e("RESTClient", "RESTClient.convertStreamToString: "+ ioe.getMessage());
        } finally {
            try {
                is.close();
            } catch (IOException ioe) {
            	Log.e("RESTClient", "RESTClient.convertStreamToString finally: "+ ioe.getMessage());
            }
        }
        return sb.toString();
    }
	
	
}
